package org.zebias.study.netty.handle;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.zebias.study.netty.boot.ChannelStore;
import org.zebias.study.netty.codec.potobuf.SubscribeReqProto;
import org.zebias.study.netty.codec.potobuf.SubscribeRespProto;

/**
 * @ClassName SubReqServerHandle
 * @Description 服务端处理器
 * @Author zebias
 * @Date 2020/8/18 11:46
 * @Version 1.0
 **/
@ChannelHandler.Sharable
public class SubReqServerHandle extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.printf("激活设备:{%s}",ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
        // 注册设备
        if (req.getSubReqID() == 1) {
            ctx.writeAndFlush(resp(req.getSubReqID(),"register msg"));
        }else{
            if ("zebias".equalsIgnoreCase(req.getUserName())) {
                System.out.println("Service accepts client subscribe req : [" +
                        req.toString() + "]");
                ctx.writeAndFlush(resp(req.getSubReqID(),"not register msg"));
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

    private SubscribeRespProto.SubscribeResp resp(int subReqId,String msg) {
        SubscribeRespProto.SubscribeResp.Builder builder = SubscribeRespProto.SubscribeResp.newBuilder();
        builder.setSubReqID(subReqId).setRespCode(0).setDesc(msg);
        return builder.build();
    }
}
